package io.renren.msg;

import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.AioHandler;

import java.nio.ByteBuffer;

/**
 * Created by kun on 2017/5/2.
 */
public abstract class HelloAbsAioHandler implements AioHandler<Object,HelloPacket,Object>{
    @Override
    public ByteBuffer encode(HelloPacket packet, GroupContext<Object, HelloPacket, Object> groupContext, ChannelContext<Object, HelloPacket, Object> channelContext) {
        byte[] body=packet.getBody();
        int bodyLen=0;
        if (body!=null){
            bodyLen=body.length;
        }

        int allLen=HelloPacket.HEADER_LENGTH+bodyLen;

        ByteBuffer buffer=ByteBuffer.allocate(allLen);
        buffer.order(groupContext.getByteOrder());

        //写入消息头---消息头的内容就是该内容的长度
        buffer.putInt(bodyLen);

        //写入消息体
        if (body!=null){
            buffer.put(body);
        }
        return buffer;
    }

    @Override
    public HelloPacket decode(ByteBuffer buffer, ChannelContext<Object, HelloPacket, Object> channelContext) throws AioDecodeException {
        int readableLength=buffer.limit()-buffer.position();
        if (readableLength<HelloPacket.HEADER_LENGTH){
            return null;
        }

        //读取消息体的长度
        int bodyLength=buffer.getInt();

        if (bodyLength<0){
            throw new AioDecodeException("bodyLength ["+bodyLength+"]is not right,remote:"+channelContext.getClientNode());
        }

        int neededLength=HelloPacket.HEADER_LENGTH+bodyLength;
        int isDataEnough=readableLength-neededLength;
        if (isDataEnough<0){
            return null;
        }else {
            //组包成功
            HelloPacket imPacket=new HelloPacket();
            if (bodyLength>0){
                byte[] dst=new byte[bodyLength];
                buffer.get(dst);
                imPacket.setBody(dst);
            }
            return  imPacket;
        }
    }
}
